package com.ethan.controller;

import com.ethan.pojo.Article;
import com.ethan.pojo.Category;
import com.ethan.pojo.PageBean;
import com.ethan.pojo.Result;
import com.ethan.service.ArticleService;
import com.ethan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping("/add")
    public Result add(@RequestBody @Validated Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        article.setCreateUser((Integer) map.get("id"));
        articleService.add(article);
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody @Validated Article article) {
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        article.setCreateUser((Integer) map.get("id"));
        articleService.update(article);
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(Integer id) {
        articleService.delete(id);
        return Result.success();
    }

    @GetMapping("/detail")
    public Result<Article> findById(Integer id) {
        return Result.success(articleService.findById(id));
    }

    @GetMapping("/list")
    public Result<PageBean<Article>> list (
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ) {
        PageBean<Article> list = articleService.list(pageNum, pageSize, categoryId, state);
        return Result.success(list);
    }
}
